package com.lukebang.util.export.excel;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

/**
 * 
 * DownloadUtil 下午3:00:27 Copyright HEXUNz Inc. All right reserved. Email :
 * alldios@outlook.com
 * 
 */
public class DownloadUtil {
	public static void exportToBrowser(HttpServletRequest request,
			HttpServletResponse response, String fileLocation, String fileName) {
		// 重置response
		response.reset();
		try {
			// 文件长度
			File proposeFile = new File(fileLocation);
			long fSize = proposeFile.length();
			response.setContentType("application/x-download");
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Length", String.valueOf(fSize));
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
			long pos = 0;
			if (null != request.getHeader("Range")) {
				// 断点续传
				response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
				try {
					pos = Long.parseLong(request.getHeader("Range")
							.replaceAll("bytes=", "").replaceAll("-", ""));
				} catch (NumberFormatException e) {
					pos = 0;
				}
			}
			BufferedOutputStream bufferOut = new BufferedOutputStream(
					response.getOutputStream());
			InputStream inputStream = new FileInputStream(proposeFile);
			String contentRange = new StringBuffer("bytes ")
					.append(new Long(pos).toString()).append("-")
					.append(new Long(fSize - 1).toString()).append("/")
					.append(new Long(fSize).toString()).toString();
			response.setHeader("Content-Range", contentRange);
			inputStream.skip(pos);
			byte[] buffer = new byte[5 * 1024];
			int length = 0;
			while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
				bufferOut.write(buffer, 0, length);
			}
			bufferOut.flush();
			bufferOut.close();
			inputStream.close();
			FileUtils.forceDelete(proposeFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
